package com.blockchain.front.servlets.password;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.framework.http.session.Session;
import com.blockchain.framework.http.session.authentication.AuthenticationException;
import com.blockchain.framework.http.session.authentication.VerifyCodeAuthentication;
import com.blockchain.framework.resource.PromptLevel;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.front.service.common.PasswordManage;
import com.blockchain.front.servlets.Index;

public class Reset extends AbstractPasswordServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void processGet(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		forwardView(request, response, getClass());
	}

	@Override
	protected void processPost(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		String password = request.getParameter("password");
		String repassword = request.getParameter("newPassword");
		String dxverifyCode = request.getParameter("dxverifyCode");
		String phone = request.getParameter("phone");
		if (!password.equals(repassword)) {
			getController().prompt(request, response, PromptLevel.ERROR, "两次输入不符");
			forward(request, response, getController().getViewURI(request, Reset.class));
			return;
		}
		Session session = serviceSession.getSession();
		VerifyCodeAuthentication authentication = new VerifyCodeAuthentication();
		authentication.setVerifyCode(dxverifyCode);
		authentication.setVerifyCodeType("RESET" + phone);
		session.authenticateVerifyCode(authentication);
		PasswordManage passwordManage = serviceSession.getService(PasswordManage.class);
		int id = passwordManage.phoneExist(phone);
		try {
			if (id > 0) {
				passwordManage.updatePassword(password, id);
				sendRedirect(request, response, getController().getViewURI(request, Index.class));
			}
		} catch (Exception e) {
			getController().prompt(request, response, PromptLevel.ERROR, e.getMessage());
			forward(request, response, getController().getViewURI(request, Reset.class));
		}

	}

	@Override
	protected void onThrowable(HttpServletRequest request, HttpServletResponse response, Throwable throwable)
			throws ServletException, IOException {
		if (throwable instanceof AuthenticationException) {
			getController().prompt(request, response, PromptLevel.ERROR, "验证码已过期或验证码错误");
			forward(request, response, getController().getViewURI(request, Reset.class));
		}
	}

}